package app.websocket;

import cn.hutool.core.lang.Console;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Hashtable;

@Component
@ServerEndpoint("/msg")
public class WebSocketApp {
    private static Hashtable<String, Session> user = new Hashtable<>();

    @OnOpen
    public void open(Session session) {
        System.out.println(session.getId() + "已连接");
        user.put(session.getId(), session);
        send("鸡你太美");
    }

    @OnClose
    public void close(Session session) {
        System.out.println(session.getId() + "已断开连接");
        user.remove(session.getId());
    }

    @OnMessage
    public void message(String msg) {
        Console.log("接收到的信息", msg);
        if (!"null".equalsIgnoreCase(msg)) {
            send(msg);
        }
    }

    public void send(String msg) {
        try {
            for (Session session : user.values()) {
                session.getBasicRemote().sendText(msg, true);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("信息发送失败");
        }
    }
}
